<?php

namespace App\Libs\Company\SheetTemplateHandler\Report;

use App\Models\SubTask;
use App\Services\DictService;
use Illuminate\Support\Facades\Log;

class Template228 extends AbstractTemplate
{
    public $dataStartRow = 3;

    protected $dictCategoryCode = 'StarredFamilyHotel';

    public $rules = [
        'column' => [
            'start_row' => 3,
            'end_row' => ['str' => '合计', 'column' => 0],
            'rule' =>
                [
                    ['column' => 1, 'vt' => 3, 'vt_val' => 'StarredFamilyHotel'],
                    ['column' => 5, 'vt' => 1],
                    ['column' => 6, 'vt' => 2],
                    ['column' => 7, 'vt' => 2],
                ],
        ],
        'cell' => [],
        'dict' => [
            'start_row' => 3,
            'end_row' => ['str' => '合计', 'column' => 0],
            'rule' => [
                'column' => 1,
                'vt' => 1,
                'vt_val' => 'StarredFamilyHotel',
            ],
        ],
    ];

    public function generateReport()
    {
        $this->renderHeader();
        $this->output['sheets']['sheet-01']['cellData']['0']['0'] = $this->createTitleCell($this->subTask->task->name);

        $dicts = DictService::getList($this->dictCategoryCode, $this->subTask->district_id);
        $sn = 1;
        foreach ($dicts as $value) {
            $this->output['sheets']['sheet-01']['cellData'][] = [
                ['v' => $sn++, 's' => 'CENTER'],
                ['v' => $value->dict_code, 's' => 'CENTER'],
                ['v' => $value->extra['星级'] ?? '', 's' => 'CENTER'],
                ['v' => $value->extra['客房数'] ?? '', 's' => 'CENTER', 't' => 1],
                ['v' => $value->extra['床位数'] ?? '', 's' => 'CENTER', 't' => 1],
                ['t' => 2],
                ['t' => 2],
                ['t' => 2],
            ];

            $this->dataEndRow++;
        }

        $this->dataEndRow--;
        $this->renderFooter();
        return $this->output;
    }

    public function getData()
    {
        if (empty($this->subTask) || $this->subTask->status != SubTask::STATUS_COMPLETED) {
            throw new \Exception('工单状态不正确');
        }
        $data = [];
        try {
            while (1) {
                $row = $this->subTask->data['sheets']['sheet-01']['cellData'][$this->dataStartRow++] ?? [];
                if (!isset($row[1]['v']) || $row[1]['v'] == '') {
                    break;
                }
                $data[$row[1]['v']] = $row;
            }
        } catch (\Throwable $th) {
            Log::error('填报表异常 id:' . $this->subTask->id);
            throw $th;
        }
        return $data;
    }
}
